package com.example;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

public class Receptionist extends BaseRole {

    // 构造方法调用 BaseRole 的构造
    public Receptionist(String userId, String username, String passwordHash, String role, LocalDateTime registrationTime, String phoneNumber) {
        super(userId, username, passwordHash, role, registrationTime, phoneNumber);
    }

    public void showMenu() {
        // 定义菜单选项与操作的映射（键为选项号，值为对应方法）
        Map<Integer, Runnable> options = new HashMap<>();
        options.put(0, null);
        options.put(1, this::listAllMovies);
        options.put(2, this::listAllScreenings);
        options.put(3, this::listSpecificScreening);
        options.put(4, this::sellTickets);
        options.put(5, this::refundTicket);
        options.put(6, this::sellSnacks);  // 新增零食销售选项

        // 调用 BaseRole 的通用菜单循环（标题 + 选项映射）
        menuLoop("前台菜单", options);
    }

    protected String getOptionName(int choice) {
        switch (choice) {
            case 0: return "返回上一级菜单（退出登录）";
            case 1: return "列出所有正在上映影片的信息";
            case 2: return "列出所有场次的信息";
            case 3: return "列出指定电影和场次的信息";
            case 4: return "售票功能";
            case 5: return "退票功能";
            case 6: return "销售零食";  // 新增选项描述
            default: return "未知选项";
        }
    }
    private void listAllMovies() {
        System.out.println("\n=== 所有正在上映影片的信息 ===");
        for (Movie movie : CinemaSystem.movies) {
            System.out.println("片名: " + movie.getTitle());
            System.out.println("导演: " + movie.getDirector());
            System.out.println("主演: " + movie.getActors());
            System.out.println("剧情简介: " + movie.getSynopsis());
            System.out.println("时长: " + movie.getDuration() + " 分钟");
            System.out.println("评分: " + movie.getRating());
            System.out.println("------------------------");
        }
    }

    private void listAllScreenings() {
        System.out.println("1. 最近一周");
        System.out.println("2. 当日");
        System.out.println("3. 近3日");
        System.out.print("请选择查看范围: ");
        int rangeChoice = Input.getValidIntInput(1,3);

        LocalDateTime start;
        LocalDateTime end;

        switch (rangeChoice) {
            case 1:
                start = LocalDateTime.now();
                end = start.plusDays(7);
                break;
            case 2:
                start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
                end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
                break;
            case 3:
                start = LocalDateTime.now();
                end = start.plusDays(3);
                break;
            default:
                System.out.println("无效的选择，默认显示最近一周的场次。");
                start = LocalDateTime.now();
                end = start.plusDays(7);
        }

        System.out.println("\n=== 符合条件的场次信息 ===");
        for (Screening screening : CinemaSystem.screenings) {
            if (!screening.getStartTime().isBefore(start) && !screening.getStartTime().isAfter(end)) {
                System.out.println(screening);
            }
        }
    }
    private void listSpecificScreening() {
        System.out.print("请输入片名: ");
        String title = Input.getValidStringInput();
        System.out.print("请输入场次编号: ");
        int screeningIndex = Input.getValidIntInput(0,Integer.MAX_VALUE) - 1;

        if (screeningIndex < 0 || screeningIndex >= CinemaSystem.screenings.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Screening screening = CinemaSystem.screenings.get(screeningIndex);
        if (!screening.getMovie().getTitle().equals(title)) {
            System.out.println("输入的片名与场次不匹配！");
            return;
        }

        ScreeningRoom room = screening.getRoom();
        int totalSeats = room.getRows() * room.getSeatsPerRow();
        int availableSeats = 0;
        for (int i = 0; i < room.getRows(); i++) {
            for (int j = 0; j < room.getSeatsPerRow(); j++) {
                if (room.isSeatAvailable(i, j)) {
                    availableSeats++;
                }
            }
        }

        System.out.println("总座位数: " + totalSeats);
        System.out.println("空闲座位数: " + availableSeats);
        room.displaySeats();
    }

    private void sellTickets() {
        // 直接输入场次编号
        System.out.print("请输入场次编号: ");
        int screeningIndex = Input.getValidIntInput(0, Integer.MAX_VALUE) - 1;

        if (screeningIndex < 0 || screeningIndex >= CinemaSystem.screenings.size()) {
            System.out.println("无效的场次编号！");
            return;
        }

        Screening screening = CinemaSystem.screenings.get(screeningIndex);
        ScreeningRoom room = screening.getRoom();
        room.displaySeats();

        System.out.print("请输入要购买的座位数量: ");
        int seatCount = Input.getValidIntInput(0, Integer.MAX_VALUE);
        List<Integer> rows = new ArrayList<>();
        List<Integer> seats = new ArrayList<>();
        List<Boolean> isChildTicket = new ArrayList<>();

        for (int i = 0; i < seatCount; i++) {
            System.out.print("请输入第 " + (i + 1) + " 个座位的排号: ");
            int row = Input.getValidIntInput(0, Integer.MAX_VALUE) - 1;
            System.out.print("请输入第 " + (i + 1) + " 个座位的座位号: ");
            int seat = Input.getValidIntInput(0, Integer.MAX_VALUE) - 1;

            if (!room.isSeatAvailable(row, seat)) {
                System.out.println("该座位已被预订，请重新选择！");
                return;
            }

            rows.add(row);
            seats.add(seat);

            System.out.print("第 " + (i + 1) + " 张票是否为儿童票？(Y/N): ");
            String isChild = Input.getValidStringInput();
            isChildTicket.add(isChild.equalsIgnoreCase("Y"));
        }

        double totalAmount = 0;
        for (int i = 0; i < seatCount; i++) {
            int row = rows.get(i);
            int seat = seats.get(i);
            room.bookSeat(row, seat);

            double price = screening.getPrice();
            // 早上10点场打9折
            if (screening.getStartTime().getHour() == 10) {
                price *= 0.9;
            }
            // 儿童票打5折
            if (isChildTicket.get(i)) {
                price *= 0.5;
            }
            totalAmount += price;
        }

        String orderId = UUID.randomUUID().toString();
        String username = "顾客";
        LocalDateTime orderTime = LocalDateTime.now();

        for (int i = 0; i < seatCount; i++) {
            int row = rows.get(i);
            int seat = seats.get(i);
            double price = screening.getPrice();
            if (screening.getStartTime().getHour() == 10) {
                price *= 0.9;
            }
            if (isChildTicket.get(i)) {
                price *= 0.5;
            }
            Order newOrder = new Order(orderId, username, screening, row, seat, price, orderTime);
            CinemaSystem.orders.add(newOrder);
        }

        Logger.log(orderTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + " - 操作人: " + this.getUsername() + " - 售票成功，电子票号: " + orderId + "，片名: " + screening.getMovie().getTitle());

        System.out.println("购票成功！订单信息如下:");
        System.out.println("电子票号: " + orderId);
        System.out.println("片名: " + screening.getMovie().getTitle());
        System.out.println("场次: " + screening.getStartTime());
        System.out.print("座位号: ");
        for (int i = 0; i < seatCount; i++) {
            System.out.print((rows.get(i) + 1) + "排" + (seats.get(i) + 1) + "座 ");
        }
        System.out.println();
        System.out.println("支付金额: ￥" + totalAmount);
    }

    private void refundTicket() {
        System.out.print("请输入电子票号: ");
        String orderId = Input.getValidStringInput();

        Order orderToRefund = null;
        for (Order order : CinemaSystem.orders) {
            if (order.getOrderId().equals(orderId)) {
                orderToRefund = order;
                break;
            }
        }

        if (orderToRefund == null) {
            System.out.println("未找到该订单！");
            return;
        }

        LocalDateTime screeningTime = orderToRefund.getScreening().getStartTime();
        LocalDateTime now = LocalDateTime.now();
        long hoursUntilScreening = ChronoUnit.HOURS.between(now, screeningTime);

        if (hoursUntilScreening < 1) {
            System.out.println("电影即将上映，不允许退票！");
            return;
        }

        double refundAmount;
        if (hoursUntilScreening >= 24) {
            refundAmount = orderToRefund.getAmount();
        } else {
            refundAmount = orderToRefund.getAmount() * 0.9;
        }

        Screening screening = orderToRefund.getScreening();
        ScreeningRoom room = screening.getRoom();
        room.cancelSeat(orderToRefund.getRow(), orderToRefund.getSeat());

        CinemaSystem.orders.remove(orderToRefund);
        

        orderToRefund.refund(refundAmount);

        System.out.println("退票成功！退还金额: ¥" + refundAmount);
    }

    private void sellSnacks() {
        System.out.println("\n=== 零食销售 ===");
        listAvailableSnacks();  // 展示可选零食
    
        while (true) {
            System.out.print("请输入要购买的零食名称（输入0结束购买）: ");
            String snackName = Input.getValidStringInput();
            if (snackName.equals("0")) break;  // 输入0结束购买
    
            Snack targetSnack = findSnackByName(snackName);
            if (targetSnack == null) {
                System.out.println("错误：未找到该零食！");
                continue;
            }
    
            if (targetSnack.getStock() <= 0) {
                System.out.println("错误：" + snackName + "库存不足！");
                continue;
            }
    
            System.out.print("请输入购买数量（当前库存：" + targetSnack.getStock() + "）: ");
            int count = Input.getValidIntInput(1, targetSnack.getStock());
    
            // 扣减库存
            targetSnack.setStock(targetSnack.getStock() - count);
            double totalCost = count * targetSnack.getPrice();
    
            // 记录销售日志
            LocalDateTime now = LocalDateTime.now();
            Logger.log(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + 
                " - 操作人: " + this.getUsername() + 
                " - 售出零食: " + snackName + " x" + count + 
                "，金额: ￥" + totalCost);
    
            System.out.println("购买成功！" + snackName + " x" + count + "，金额: ￥" + totalCost);
        }
    
        System.out.println("零食销售流程结束！");
    }
    
    // 辅助方法：展示所有可选零食
    private void listAvailableSnacks() {
        System.out.println("\n=== 可选零食列表 ===");
        for (Snack snack : CinemaSystem.snacks) {
            System.out.printf("%s - 单价: ￥%.1f  库存: %d\n", 
                snack.getName(), snack.getPrice(), snack.getStock());
        }
    }
    
    // 辅助方法：根据名称查找零食
    private Snack findSnackByName(String name) {
        for (Snack snack : CinemaSystem.snacks) {
            if (snack.getName().equalsIgnoreCase(name)) {
                return snack;
            }
        }
        return null;
    }
}